﻿using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Newtonsoft.Json;
using Radius.Admin.Core;
using Rmac.DataBase.Entity;
using Rmac.Uitls;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Rmac
{
    public class MaterialIssueSerivce
    {
        [Inject]
        private SqlSugarRepository<MaterialIssue> _sqlSugarRepository { set; get; }

        [Inject]
        private SqlSugarRepository<MaterialIssueChildBatch> _issueChildBatchRepository { set; get; }

        [Inject]
        private SqlSugarRepository<MaterialIssueChild> _issueChildRepository { set; get; }
        

        public MaterialIssueSerivce(SqlSugarRepository<MaterialIssue> sqlSugarRepository,
            SqlSugarRepository<MaterialIssueChildBatch> issueChildBatchRepository, 
            SqlSugarRepository<MaterialIssueChild> issueChildRepository)
        {
            _sqlSugarRepository = sqlSugarRepository;
            _issueChildBatchRepository = issueChildBatchRepository;
            _issueChildRepository = issueChildRepository;
        }

        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<MaterialIssue>> QueryIssueList(MaterialIssue issue)
        {
            return await _sqlSugarRepository.AsQueryable().Includes(x => x.FG_InvChild,y=>y.FG_Issue
            .MappingField(a => a.Id,()=> y.Pid))
            .WhereIF(!string.IsNullOrEmpty(issue.NO), x => x.NO == issue.NO)
            .WhereIF(issue.Id > 0,x=> x.Id == issue.Id)
            .WhereIF(Convert.ToInt32(issue.Status) > 0, x => x.Status == issue.Status)
            .OrderByDescending(x => x.Id)
            .ToListAsync();
        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="issue"></param>
        /// <returns></returns>
        public async Task<object> DeleteIssue(MaterialIssue issue)
        {
            return await _sqlSugarRepository.Context
            .DeleteNav<MaterialIssue>(it => it.Id == issue.Id)
            .Include(x => x.FG_InvChild)
            .ExecuteCommandAsync();
        }

        /// <summary>
        /// 保存工单
        /// </summary>
        /// <param name="issue"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<object> ScanQrCodeSaveIssue(MaterialIssue issue)
        {
            if (await _sqlSugarRepository.IsAnyAsync(x => x.NO == issue.NO))
            {
                throw new Exception("此工单已经存在！");
            }
            return await _sqlSugarRepository.Context.InsertNav(issue)
            .Include(x => x.FG_InvChild)
            .ExecuteCommandAsync();
        }

        /// <summary>
        /// 插入工单明细材料批次记录
        /// </summary>
        /// <param name="issue"></param>
        /// <returns></returns>
        public async Task<object> InsertIssueChildBatch(MaterialIssueChildBatch issue)
        {
            var issueChildInv = await _issueChildRepository.GetFirstAsync(x => 
            x.InventoryID == issue.InventoryID && 
            x.Pid == issue.Pid &&
            x.RountNo == issue.RountNo);
            if (issueChildInv is null)
                return await _issueChildBatchRepository.AsInsertable(issue).ExecuteCommandAsync();
            {
                issueChildInv.ActQty ??= 0;
                issueChildInv.ActQty += issue.ActQty;
                if (string.IsNullOrEmpty(issueChildInv.ProjectBatch))
                {
                    issueChildInv.ProjectBatch = issue.ProjectBatch;
                }
                else
                {
                    issueChildInv.ProjectBatch += "/" + issue.ProjectBatch;
                }

                if((issueChildInv.ActQty >= issueChildInv.LowerLimit && issueChildInv.ActQty <= issueChildInv.TopLimit) || issue.ActQty > issueChildInv.TopLimit)
                {
                    issueChildInv.Status = 4;
                }
                else
                {
                    issueChildInv.Status = 2;
                }

                issueChildInv.GrossWeight = issue.GrossWeight;
                issueChildInv.Tare = issue.Tare;
                await _issueChildRepository.AsUpdateable(issueChildInv)
                    .UpdateColumns(x => new
                    {
                        x.ActQty, x.Status,x.ProjectBatch,x.GrossWeight,x.Tare
                    })
                    .ExecuteCommandAsync();
            }

            return await _issueChildBatchRepository.AsInsertable(issue).ExecuteCommandAsync();
        }


        /// <summary>
        /// 插入明细配方外材料记录
        /// </summary>
        /// <param name="issue"></param>
        /// <returns></returns>
        public async Task<object> InsertIssueChildOutInv(MaterialIssueChild issue)
        {
            issue.IsBomOutInv = BomInvInOrOut.Out;
            var childList = await _issueChildRepository.AsQueryable().Where(x => x.Pid == issue.Pid).ToListAsync();
            issue.Noid = childList.Max(x => x.Noid)+1;
            var entity = await _issueChildRepository.AsInsertable(issue).ExecuteReturnEntityAsync();
            entity.FG_Issue = await _sqlSugarRepository.GetByIdAsync(entity.Pid);
            return entity;
        }

        /// <summary>
        /// 更新工单明细物料中的计划量
        /// </summary>
        /// <param name="issue"></param>
        /// <returns></returns>
        public async Task<object> UpdateIssueChildPlanQty(MaterialIssueChild issue)
        {
            var entity = await _issueChildRepository.GetByIdAsync(issue.Id);
            entity.AddQty ??= 0;
            entity.AddQty += issue.PlanQty;
            return await _issueChildRepository.Context.Updateable(entity)
                //.PublicSetColumns(x => x.AddQty, t=> t.AddQty + issue.AddQty)
                .UpdateColumns(x => new { x.AddQty })
            .ExecuteCommandAsync();
        }

        /// <summary>
        /// 更新工单明细物料状态
        /// </summary>
        /// <param name="issue"></param>
        /// <returns></returns>
        public async Task<object> UpdateIssueChildStatus(MaterialIssueChild issue)
        {
            return await _issueChildRepository.Context.Updateable(issue)
                .UpdateColumns(x => new { x.Status }).Where(x => x.Id == issue.Id)
            .ExecuteCommandAsync();
        }

        /// <summary>
        /// 更新工单明细物料状态
        /// </summary>
        /// <param name="issue"></param>
        /// <returns></returns>
        public async Task<object> UpdateIssueStatus(MaterialIssue issue)
        {
            var childs = await _issueChildRepository.AsQueryable().Where(x => x.Pid == issue.Id).ToListAsync();
            foreach (var item in childs)
            {
                item.Status = 4;
            }

            await _issueChildRepository.Context.Updateable(childs).ExecuteCommandAsync();
            issue.Status = "4";
            return await _sqlSugarRepository.Context.Updateable(issue)
                .UpdateColumns(x => new { x.Status }).Where(x => x.Id == issue.Id)
            .ExecuteCommandAsync();
        }

        public async Task<string> GetIssueFinshDetail(MaterialIssue issue)
        {
            var issueEntity = await _sqlSugarRepository.AsQueryable()
                .Includes(x => x.FG_InvChild)
                .Includes(x => x.FG_InvChildBatch)
                .Where(x => x.Id == issue.Id && x.Status == "4").FirstAsync();
            var result = new
            {
                NO = issueEntity.NO,
                Date = issueEntity.Date,
                FG_InvChild = new List<object>()
            };
            foreach (var item in issueEntity.FG_InvChild)
            {
                result.FG_InvChild.Add(new
                {
                    RountNo = item.RountNo,
                    InventoryID = item.InventoryID,
                    ActQty = item.ActQty,
                    ProjectBatch = item.ProjectBatch
                });
            }
            return StringUtils.Compress(JsonConvert.SerializeObject(result));
        }
    }
}
